import json

from django_redis import get_redis_connection
from AskDoctor.models import DoctorModel

def get_user_coupon_list(user_id):
    redis = get_redis_connection('coupon')
    coupon_list = redis.keys(f"{user_id}:*")

    coupon_id_list = [i.decode() for i in coupon_list]

    coupon_data = []
    for coupon_key in coupon_id_list:

        coupon_item = {"user_coupon_id":int(coupon_key.split(':')[-1])}

        coupon_hash = redis.hgetall(coupon_key)

        for key,value in coupon_hash.items():
            key = key.decode()
            value = value.decode()

            if key in ['to_direction','to_category','to_course']:
                value = json.loads(value)

            coupon_item[key] = value
        coupon_data.append(coupon_item)
    return coupon_data




def get_user_enable_coupon_list(user_id):

    redis = get_redis_connection('cart')
    cart_hash = redis.hgetall(f"cart_{user_id}")

    course_id_list = {int(key.decode()) for key,value in cart_hash.items() if value == b'1'}
    course_list = DoctorModel.objects.filter(id__in = course_id_list,is_deleted=False,is_show=True)

    direction_id_list = set()
    category_id_list = set()

    for course in course_list:
        direction_id_list.add(course.direction.id)
        category_id_list.add(course.category.id)

    coupon_data = get_user_coupon_list(user_id)

    enable_coupon_list = []

    for item in coupon_data:
        coupon_type = int(item.get('coupon_type'))

        if coupon_type == 0:
            item['enable_course'] = "__all__"
            enable_coupon_list.append(item)

        elif coupon_type == 1:
            coupon_direction = {direction_item['direction__id'] for direction_item in item.get('to_direction')}
            ret = coupon_direction & direction_id_list

            if len(ret)>0:
                item['enable_course'] = {int(course.id) for course in course_list if course.direction.id in ret}
                enable_coupon_list.append(item)

        elif coupon_type == 2:
            coupon_category = {category_item['category__id'] for category_item in item.get("to_category")}
            ret = coupon_category & category_id_list

            if len(ret)>0:
                item['enable_course'] = {int(course.id) for course in course_list if course.category.id in ret}
                enable_coupon_list.append(item)

        elif coupon_type ==3:
            coupon_course = {course_item['course__id'] for course_item in item.get('to_course')}
            ret = coupon_course & course_id_list

            if len(ret)>0:
                item['enable_course'] ={int(course.id) for course in course_list if course.id in ret}
                enable_coupon_list.append(item)

    return enable_coupon_list







